const app = getApp();
var baseUrl = app.globalData.baseUrl
var token = undefined;
const ossToken = app.globalData.ossToken
var sendRequest = function (url, method, data = {}, header = {}) {
  var promise = new Promise(function (resolve, reject) {
    wx.showLoading({
      title: '加载中',
    })
    token = wx.getStorageSync('token');
    wx.request({
      url: baseUrl + url,
      method: method,
      data: data,
      header: {
        "token": token,
      },
      success: function (data) {
        wx.hideLoading()
        if (data.data.code == 505) {
          wx.showToast({
            title: data.data.msg,
            icon: 'none',
          })
          wx.navigateTo({
            url: '/pages/person/registered/index'
          })
          return
        } else if (data.data.code == 0) {
          resolve(data);
        } else {
          wx.showToast({
            title: data.data.msg,
            icon: 'none',
          })
        }
      },
      fail: function (data) {
        wx.showToast({
          title: '系统内部错误，请联系管理员',
          icon: 'none',
        })
        reject(data);
      }
    })
  })
  return promise
}
const getOssToken = require('./util.js');
console.log(getOssToken);
var upLoadFiles = function (filePath) {
  const ossToken = getOssToken.getOssToken()
  console.log(ossToken);
  const {
    host,
    accessKeyId,
    policy,
    signature,
    dir

  } = getOssToken.getOssToken()
  const path = dir
  const aliyunFileKey = path + new Date().getTime() + Math.floor(Math.random() * 150) + '.png';
  var promise = new Promise(function (resolve, reject) {
    wx.uploadFile({
      filePath: filePath,
      name: 'file',
      url: host,
      formData: {
        'key': aliyunFileKey,
        'policy': policy,
        'OSSAccessKeyId': accessKeyId,
        'signature': signature,
        // 'success_action_status': '200',
      },
      success: (res) => {
        console.log("成功", res);
        // const image = host + '/' + aliyunFileKey
        const image = host + aliyunFileKey
        resolve(image)
        // return image
      },
      fail: (err) => {
        reject(err)
        console.log('失败', err);
      }
    })
  })
  return promise
}
module.exports = {
  sendRequest: sendRequest,
  upLoadFiles: upLoadFiles
}